package zzxkj.blog.schedules;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import zzxkj.blog.common.lang.Consts;
import zzxkj.blog.service.BlogService;
import zzxkj.blog.utils.RedisUtil;

/**
 * @author zzxkj
 */
@Slf4j
@Component
public class DayViewCountSyncTask {


    private final BlogService blogService;
    private final RedisUtil redisUtil;


    public DayViewCountSyncTask(BlogService blogService, RedisUtil redisUtil) {
        this.blogService = blogService;
        this.redisUtil = redisUtil;
    }

    /**
     * 每天0点初始化，新增天记录
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void dayViewInit(){
        log.info("{} Start Create NewDayViews Record", new DateTime());
        Integer views = blogService.getNowDayViews();
        Integer result = null;
        //新增DB当天的记录数据
        if(views == null){
            //String key = blogService.getTodayTimeKey(Consts.DAY_VIEW_DATA_KEY_PREFIX);
            result = blogService.dayViewInit();
            //redisUtils.set(key, 0, 3600*24);
        }
        if (result == null && views == null ){
            log.error("{} Fail Create NewDayViews Record", new DateTime());
        }else {
            log.info("{} Success dayViewInit", new DateTime());
            //新的一天初始化
            blogService.initCacheChartData();
        }
    }

    /**
     *每5分钟同步天数
     * */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void blogViewCountSync(){
        Object dayViewsJson = redisUtil.lGetIndex(Consts.CHART_VIEW_DATA_KEY, -1);
        JSONObject dayViews = JSONUtil.parseObj(dayViewsJson);
        Integer views = dayViews.getInt("views");
        if(views == null){
            log.error("Day views is null");
        }
        blogService.updateDayViews(views);
        log.info("Update day views update:{}", views.toString());
    }

}
